package com.hkts.management.drivercomment.service.serviceimpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.hkts.management.common.utils.SnowFlakeUtil;
import com.hkts.management.drivercomment.entity.DriverComment;
import com.hkts.management.drivercomment.mapper.DriverCommentMapper;
import com.hkts.management.drivercomment.service.IDriverCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.management.es.EsSearchUtil;
import com.hkts.management.feign.FeignInterface;
import com.hkts.management.feign.FrontInterface;
import com.hkts.management.model.TO.HontUserTo;
import com.hkts.management.model.enums.OrderStatusEnum;
import com.hkts.management.model.enums.OrderTypeEnum;
import com.hkts.management.order.entity.HktsOrder;
import com.hkts.management.order.mapper.HktsOrderMapper;
import com.hkts.management.orderrecord.service.IHktsOrderRecordService;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.hkts.management.es.constants.EsCargoConstants.*;
import static com.hkts.management.es.constants.EsCargoConstants.CARGO_ORDER_INDEX;
import static java.util.Objects.isNull;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hml
 * @since 2021-05-20
 */
@Slf4j
@Service
@Transactional
public class DriverCommentServiceImpl extends ServiceImpl<DriverCommentMapper, DriverComment> implements IDriverCommentService {


    @Autowired
    private DriverCommentMapper driverCommentMapper;
    @Autowired
    private HktsOrderMapper orderMapper;
    @Autowired
    private FeignInterface feignInterface;
    @Autowired
    public FrontInterface frontInterface;
    @Autowired
    private IHktsOrderRecordService iHktsOrderRecordService;

    @Autowired
    private EsSearchUtil esSearchUtil;
    @Override
    public IPage<DriverComment> selectPage(Page<DriverComment> page, DriverComment driverComment) {
        QueryWrapper<DriverComment> query = Wrappers.query();
        QueryWrapper<DriverComment> entityWrapper = getEntityWrapper(query, driverComment);
        return driverCommentMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<DriverComment> selectList(DriverComment driverComment) {
        QueryWrapper<DriverComment> query = Wrappers.query();
        query.lambda().eq(!driverComment.getDriverId().isEmpty(),DriverComment::getDriverId,driverComment.getDriverId());
        return driverCommentMapper.selectList(query);
    }
    @Override
    public DriverComment selectComment(String orderId) {
        QueryWrapper<DriverComment> query = Wrappers.query();
        query.lambda().eq(!orderId.isEmpty(),DriverComment::getOrderId,orderId);
        DriverComment driverComment = driverCommentMapper.selectOne(query);
        HktsOrder hktsOrder = orderMapper.selectById(orderId);
        driverComment.setOrderStatus(hktsOrder.getShipperOrderStatus().getValue());
        return driverComment;
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<DriverComment> getEntityWrapper(QueryWrapper<DriverComment> entityWrapper, DriverComment driverComment) {

        return entityWrapper;
    }
    @Override
    public void updateOrderOnEs(String id,OrderTypeEnum orderType,Integer subState){
        //同步es数据
        String orderId=ORDER_PREFIX+id;
        Map<String,Object> map= esSearchUtil.getEsDateById(CARGO_ORDER_INDEX,orderId);
        if(map==null||Integer.parseInt(map.get("count").toString())==0) {
            log.error("同步订单数据，es查询数据为空{}", map);
            return;
        }
        Map<String, Object> orderEsData = new ConcurrentHashMap<>(2);
        orderEsData.put(SHIPPERORDERSTATUS,orderType.getValue());
        orderEsData.put(SHIPPERORDERSUBSTATE,subState);
        log.info("es同步订单数据{},订单id{}",orderEsData,orderId);
        //TODO es同步数据
        esSearchUtil.updateToEs(orderEsData,CARGO_ORDER_INDEX,orderId);
    }
    @Override
    public Result<DriverComment> saveDrverComment(DriverComment driverComment){
        QueryWrapper<DriverComment> query = Wrappers.query();
        query.lambda().eq(DriverComment::getOrderId,driverComment.getOrderId());
        DriverComment one = driverCommentMapper.selectOne(query);
        if (!isNull(one)){
           return ResultUtil.error("该订单已评论！");
        }
        driverComment.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        driverComment.setCreateTime(localDateTime);
        driverComment.setUpdateTime(localDateTime);
        driverCommentMapper.insert(driverComment);
        orderMapper.updateShipperByOrderId(driverComment.getOrderId(), OrderTypeEnum.DONE, OrderStatusEnum.DONE.getValue(),LocalDateTime.now());
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        iHktsOrderRecordService.addOrderRecord(driverComment.getOrderId(),hontUserTo.getNickName(),OrderStatusEnum.DONE.getValue());
        //TODO es同步数据
        updateOrderOnEs(driverComment.getOrderId(),OrderTypeEnum.DONE,OrderStatusEnum.DONE.getValue());
        //添加司机详情数据
        QueryWrapper<DriverComment> queryGood = Wrappers.query();
        queryGood.lambda().eq(DriverComment::getDriverId,driverComment.getDriverId())
        .eq(DriverComment::getScore,3);
        Integer goods=driverCommentMapper.selectCount(queryGood);
        QueryWrapper<DriverComment> querysTotal = Wrappers.query();
        querysTotal.lambda().eq(DriverComment::getDriverId,driverComment.getDriverId());
        Integer total=driverCommentMapper.selectCount(querysTotal);
        BigDecimal applauseRate=new BigDecimal(0);
        if(goods>0&&total>0){
            BigDecimal a= new BigDecimal(goods);
            BigDecimal b= new BigDecimal(total);
             applauseRate= a.multiply(new BigDecimal(100)).divide(b,2,BigDecimal.ROUND_HALF_UP);
        }
        QueryWrapper<HktsOrder> queryOrder = Wrappers.query();
        queryOrder.lambda().eq(HktsOrder::getDriverId,driverComment.getDriverId())
                .eq(HktsOrder::getOrderStatus,OrderTypeEnum.DONE);
        Integer orderCount=orderMapper.selectCount(queryOrder);
        frontInterface.addDriverDetail(driverComment.getDriverId(),applauseRate,orderCount);
        return ResultUtil.data(driverComment);
    }

    @Override
    public Result<Object> getCredit(String driverId){
        QueryWrapper<DriverComment> query = Wrappers.query();
        query.lambda().eq(!driverId.isEmpty(),DriverComment::getDriverId,driverId);
        List<DriverComment> driverComments = driverCommentMapper.selectList(query);

        QueryWrapper<HktsOrder> Query = Wrappers.query();
        Query.lambda().eq(HktsOrder::getDriverId, driverId)
                .and(wrapper -> wrapper.eq(HktsOrder::getOrderStatus, 3).or().eq(HktsOrder::getOrderStatus, 4));
        Integer orderCount = orderMapper.selectCount(Query);

        Map<String,Object> resultMap = new HashMap<>();
        if (driverComments.size() < 3){
            resultMap.put("dealNum",orderCount);
            resultMap.put("feedBack",driverComments.size());
            return ResultUtil.data(resultMap);
        }

        int count = 0;
        for (int i = 0; i < driverComments.size(); i++) {
            Integer score = driverComments.get(i).getScore();
            if (score == 3){
                count ++;
            }
        }
        String bs =  bs(count, driverComments.size()) + "%";

        resultMap.put("dealNum",orderCount);
        resultMap.put("feedBack",bs);
        return ResultUtil.data(resultMap);
    }
    public int bs(int a ,int b){
        return (int)((new BigDecimal((float) a / b).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())*100);
    }
}
